package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.mongo.UserLocationDTO;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author anshuai
 * @create 2021-02-08 22:40
 */
@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存地址位置
     * @param latitude 纬度
     * @param longitude 经度
     * @param address
     * @param userId 用户id
     */
    @Override
    public void save(Double latitude, Double longitude, String address, Long userId) {
        //1. 判断MongoDB中有没有用户的地址位置信息
        Query query = new Query(Criteria.where("userId").is(userId));
        if (mongoTemplate.exists(query, UserLocation.class)){
            //数据库中已有用户的地理位置，更新
            GeoJsonPoint point = new GeoJsonPoint(longitude,latitude);
            Update update = new Update()
                    .set("address",address)
                    .set("updated",System.currentTimeMillis())
                    .set("location",point);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }else {
            //数据库中没有用户的地址位置，保存
            UserLocation location = new UserLocation();
            location.setId(ObjectId.get());
            location.setAddress(address);
            location.setCreated(System.currentTimeMillis());
            location.setLastUpdated(System.currentTimeMillis());
            location.setLocation(new GeoJsonPoint(longitude,latitude));
            location.setUpdated(System.currentTimeMillis());
            location.setUserId(userId);

            mongoTemplate.save(location);
        }
    }

    /**
     * 搜索某一用户附近的人
     * @param userId 用户
     * @param miles 搜索范围，单位：米
     * @return
     */
    @Override
    public List<UserLocationDTO> searchNear(Long userId, Integer miles) {
        //1. 查询得到用户自己的位置
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);
        GeoJsonPoint point = userLocation.getLocation();

        //2. 以用户自己的位置为圆心，以metre范围为半径，划圆
        Distance distance = new Distance(miles/1000, Metrics.KILOMETERS);
        Circle circle = new Circle(point, distance);

        //3. 使用MongoDB搜索圆内的用户
        Query query = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query, UserLocation.class);

        //4. 转换成UserLocationDTO
        return UserLocationDTO.translateList(userLocationList);
    }
}
